using System.ComponentModel.DataAnnotations;

namespace DocumentCreationSystem.Models
{
    /// <summary>
    /// 写书流程配置模型
    /// </summary>
    public class WritingWorkflowConfig
    {
        [Key]
        public int Id { get; set; }

        /// <summary>
        /// 配置名称
        /// </summary>
        public string Name { get; set; } = string.Empty;

        /// <summary>
        /// 配置描述
        /// </summary>
        public string Description { get; set; } = string.Empty;

        /// <summary>
        /// 是否为默认配置
        /// </summary>
        public bool IsDefault { get; set; }

        /// <summary>
        /// 创建时间
        /// </summary>
        public DateTime CreatedAt { get; set; } = DateTime.Now;

        /// <summary>
        /// 更新时间
        /// </summary>
        public DateTime UpdatedAt { get; set; } = DateTime.Now;

        #region 基础流程设定

        /// <summary>
        /// 是否启用全书大纲生成
        /// </summary>
        public bool EnableOverallOutlineGeneration { get; set; } = true;

        /// <summary>
        /// 是否启用世界设定生成
        /// </summary>
        public bool EnableWorldSettingGeneration { get; set; } = true;

        /// <summary>
        /// 是否启用卷宗大纲生成
        /// </summary>
        public bool EnableVolumeOutlineGeneration { get; set; } = true;

        /// <summary>
        /// 是否启用章节细纲生成
        /// </summary>
        public bool EnableChapterOutlineGeneration { get; set; } = true;

        /// <summary>
        /// 是否启用章节正文生成
        /// </summary>
        public bool EnableChapterContentGeneration { get; set; } = true;

        /// <summary>
        /// 是否启用时间线更新
        /// </summary>
        public bool EnableTimelineUpdate { get; set; } = true;

        #endregion

        #region 生成参数设定

        /// <summary>
        /// 全书大纲生成的最大Token数
        /// </summary>
        public int OverallOutlineMaxTokens { get; set; } = 4000;

        /// <summary>
        /// 全书大纲生成的Temperature
        /// </summary>
        public float OverallOutlineTemperature { get; set; } = 0.7f;

        /// <summary>
        /// 世界设定生成的最大Token数
        /// </summary>
        public int WorldSettingMaxTokens { get; set; } = 6000;

        /// <summary>
        /// 世界设定生成的Temperature
        /// </summary>
        public float WorldSettingTemperature { get; set; } = 0.6f;

        /// <summary>
        /// 卷宗大纲生成的最大Token数
        /// </summary>
        public int VolumeOutlineMaxTokens { get; set; } = 3000;

        /// <summary>
        /// 卷宗大纲生成的Temperature
        /// </summary>
        public float VolumeOutlineTemperature { get; set; } = 0.7f;

        /// <summary>
        /// 章节细纲生成的最大Token数
        /// </summary>
        public int ChapterOutlineMaxTokens { get; set; } = 3000;

        /// <summary>
        /// 章节细纲生成的Temperature
        /// </summary>
        public float ChapterOutlineTemperature { get; set; } = 0.8f;

        /// <summary>
        /// 章节正文生成的最大Token数
        /// </summary>
        public int ChapterContentMaxTokens { get; set; } = 8000;

        /// <summary>
        /// 章节正文生成的Temperature
        /// </summary>
        public float ChapterContentTemperature { get; set; } = 0.9f;

        /// <summary>
        /// 时间线更新的最大Token数
        /// </summary>
        public int TimelineUpdateMaxTokens { get; set; } = 2000;

        /// <summary>
        /// 时间线更新的Temperature
        /// </summary>
        public float TimelineUpdateTemperature { get; set; } = 0.5f;

        #endregion

        #region 流程控制设定

        /// <summary>
        /// 是否启用批量生成模式
        /// </summary>
        public bool EnableBatchMode { get; set; } = false;

        /// <summary>
        /// 是否启用顺序生成模式（逐章生成）
        /// </summary>
        public bool EnableSequentialMode { get; set; } = true;

        /// <summary>
        /// 生成失败时的重试次数
        /// </summary>
        public int RetryCount { get; set; } = 3;

        /// <summary>
        /// 生成间隔时间（毫秒）
        /// </summary>
        public int GenerationInterval { get; set; } = 1000;

        /// <summary>
        /// 是否启用自动保存
        /// </summary>
        public bool EnableAutoSave { get; set; } = true;

        /// <summary>
        /// 自动保存间隔（分钟）
        /// </summary>
        public int AutoSaveInterval { get; set; } = 5;

        #endregion

        #region 内容参考设定

        /// <summary>
        /// 章节细纲生成时参考的前文章节数
        /// </summary>
        public int PreviousChaptersForOutline { get; set; } = 2;

        /// <summary>
        /// 章节正文生成时参考的前文章节数
        /// </summary>
        public int PreviousChaptersForContent { get; set; } = 3;

        /// <summary>
        /// 世界设定参考的最大文件数
        /// </summary>
        public int MaxWorldSettingFiles { get; set; } = 5;

        /// <summary>
        /// 单个世界设定文件的最大字符数
        /// </summary>
        public int MaxWorldSettingFileLength { get; set; } = 1000;

        /// <summary>
        /// 是否启用跨卷时间线参考
        /// </summary>
        public bool EnableCrossVolumeTimelineReference { get; set; } = true;

        /// <summary>
        /// 跨卷时间线参考的最大字符数
        /// </summary>
        public int MaxCrossVolumeTimelineLength { get; set; } = 1500;

        #endregion

        #region 文件输出设定

        /// <summary>
        /// 输出文件格式（txt, docx）
        /// </summary>
        public string OutputFileFormat { get; set; } = "txt";

        /// <summary>
        /// 是否启用文件名自动生成
        /// </summary>
        public bool EnableAutoFileName { get; set; } = true;

        /// <summary>
        /// 文件名模板
        /// </summary>
        public string FileNameTemplate { get; set; } = "{BookTitle}_{ChapterTitle}";

        /// <summary>
        /// 是否启用章节标题自动生成
        /// </summary>
        public bool EnableAutoChapterTitle { get; set; } = true;

        /// <summary>
        /// 是否在文件名中包含章节号
        /// </summary>
        public bool IncludeChapterNumberInFileName { get; set; } = true;

        #endregion

        #region 质量控制设定

        /// <summary>
        /// 是否启用内容一致性检查
        /// </summary>
        public bool EnableConsistencyCheck { get; set; } = true;

        /// <summary>
        /// 是否启用重复内容检测
        /// </summary>
        public bool EnableDuplicationCheck { get; set; } = true;

        /// <summary>
        /// 重复内容检测的相似度阈值（0-1）
        /// </summary>
        public float DuplicationThreshold { get; set; } = 0.8f;

        /// <summary>
        /// 是否启用字数控制
        /// </summary>
        public bool EnableWordCountControl { get; set; } = true;

        /// <summary>
        /// 字数控制的容差范围（百分比）
        /// </summary>
        public float WordCountTolerance { get; set; } = 0.2f;

        #endregion

        #region 步骤管理设定

        /// <summary>
        /// 自定义执行步骤列表
        /// </summary>
        public List<WorkflowStep> CustomSteps { get; set; } = new();

        /// <summary>
        /// 是否启用自定义步骤顺序
        /// </summary>
        public bool EnableCustomStepOrder { get; set; } = false;

        /// <summary>
        /// 是否允许跳过步骤
        /// </summary>
        public bool AllowStepSkipping { get; set; } = true;

        /// <summary>
        /// 步骤执行模式（Sequential=顺序执行, Parallel=并行执行, Custom=自定义）
        /// </summary>
        public StepExecutionMode ExecutionMode { get; set; } = StepExecutionMode.Sequential;

        #endregion

        /// <summary>
        /// 获取启用的步骤列表（按执行顺序）
        /// </summary>
        public List<WorkflowStep> GetEnabledSteps()
        {
            var steps = new List<WorkflowStep>();

            if (EnableCustomStepOrder && CustomSteps.Any())
            {
                // 使用自定义步骤顺序
                steps.AddRange(CustomSteps.Where(s => s.IsEnabled).OrderBy(s => s.Order));
            }
            else
            {
                // 使用默认步骤顺序
                if (EnableWorldSettingGeneration)
                    steps.Add(new WorkflowStep { Id = "world_setting", Name = "生成世界设定", Order = 1, IsEnabled = true });

                if (EnableOverallOutlineGeneration)
                    steps.Add(new WorkflowStep { Id = "overall_outline", Name = "生成全书大纲", Order = 2, IsEnabled = true });

                if (EnableVolumeOutlineGeneration)
                    steps.Add(new WorkflowStep { Id = "volume_outlines", Name = "生成卷宗大纲", Order = 3, IsEnabled = true });

                if (EnableChapterOutlineGeneration)
                    steps.Add(new WorkflowStep { Id = "chapter_outlines", Name = "生成章节细纲", Order = 4, IsEnabled = true });

                if (EnableChapterContentGeneration)
                    steps.Add(new WorkflowStep { Id = "chapter_content", Name = "生成章节正文", Order = 5, IsEnabled = true });

                if (EnableTimelineUpdate)
                    steps.Add(new WorkflowStep { Id = "timeline_update", Name = "更新时间线", Order = 6, IsEnabled = true });
            }

            return steps;
        }

        /// <summary>
        /// 验证步骤配置的有效性
        /// </summary>
        public (bool IsValid, List<string> Errors) ValidateSteps()
        {
            var errors = new List<string>();
            var enabledSteps = GetEnabledSteps();

            if (!enabledSteps.Any())
            {
                errors.Add("至少需要启用一个执行步骤");
            }

            // 检查必需步骤
            if (!enabledSteps.Any(s => s.Id == "overall_outline"))
            {
                errors.Add("必须启用全书大纲生成步骤");
            }

            if (!enabledSteps.Any(s => s.Id == "chapter_content"))
            {
                errors.Add("必须启用章节正文生成步骤");
            }

            // 检查步骤依赖关系
            var stepIds = enabledSteps.Select(s => s.Id).ToList();

            if (stepIds.Contains("volume_outlines") && !stepIds.Contains("overall_outline"))
            {
                errors.Add("启用卷宗大纲生成时必须先启用全书大纲生成");
            }

            if (stepIds.Contains("chapter_outlines") && !stepIds.Contains("volume_outlines"))
            {
                errors.Add("启用章节细纲生成时必须先启用卷宗大纲生成");
            }

            if (stepIds.Contains("chapter_content") && !stepIds.Contains("chapter_outlines"))
            {
                errors.Add("启用章节正文生成时必须先启用章节细纲生成");
            }

            return (errors.Count == 0, errors);
        }
    }

    /// <summary>
    /// 工作流步骤
    /// </summary>
    public class WorkflowStep
    {
        /// <summary>
        /// 步骤ID
        /// </summary>
        public string Id { get; set; } = "";

        /// <summary>
        /// 步骤名称
        /// </summary>
        public string Name { get; set; } = "";

        /// <summary>
        /// 步骤描述
        /// </summary>
        public string Description { get; set; } = "";

        /// <summary>
        /// 执行顺序
        /// </summary>
        public int Order { get; set; }

        /// <summary>
        /// 是否启用
        /// </summary>
        public bool IsEnabled { get; set; } = true;

        /// <summary>
        /// 是否必需
        /// </summary>
        public bool IsRequired { get; set; } = false;

        /// <summary>
        /// 依赖的步骤ID列表
        /// </summary>
        public List<string> Dependencies { get; set; } = new();

        /// <summary>
        /// 步骤参数
        /// </summary>
        public Dictionary<string, object> Parameters { get; set; } = new();

        /// <summary>
        /// 是否已完成
        /// </summary>
        public bool IsCompleted { get; set; } = false;

        /// <summary>
        /// 完成时间
        /// </summary>
        public DateTime? CompletedAt { get; set; }

        /// <summary>
        /// 执行结果
        /// </summary>
        public string? Result { get; set; }

        /// <summary>
        /// 错误信息
        /// </summary>
        public string? ErrorMessage { get; set; }

        /// <summary>
        /// 是否可跳过
        /// </summary>
        public bool CanSkip { get; set; } = false;

        /// <summary>
        /// 预计执行时间（分钟）
        /// </summary>
        public int EstimatedDurationMinutes { get; set; } = 5;

        /// <summary>
        /// 是否仅作为配置项，不直接执行导出操作
        /// </summary>
        public bool IsConfigurationOnly { get; set; } = false;
    }

    /// <summary>
    /// 步骤执行模式
    /// </summary>
    public enum StepExecutionMode
    {
        /// <summary>
        /// 顺序执行
        /// </summary>
        Sequential,

        /// <summary>
        /// 并行执行
        /// </summary>
        Parallel,

        /// <summary>
        /// 自定义执行
        /// </summary>
        Custom
    }
}
